<?php
namespace Php\Queue;


use Redis;
use Swoole\Database\RedisConfig;
use Swoole\Database\RedisPool;

class RedisDriver
{
	private static $config ;
	private static $handler = null;
	
	private static   $redisPool = null;
	
	private function __construct()
	{
	}
	
	public static function connect($config, $isSwoole = false)
	{
		self::$config = $config;
		if ($isSwoole) {
			if (!self::$redisPool) {
				self::longConnect();
			}
			return self::$redisPool->get();
		}
		
		if (self::$handler && self::$handler instanceof Redis) {
			return self::$handler;
		}
		
		$redis = new \Redis();
		$redis->connect(self::$config->getHost(), self::$config->getPort());
		if (self::$config->getAuth()) {
			$redis->auth(self::$config->getAuth());
		}
		$redis->select(self::$config->getSelect());
		self::$handler = $redis;
		return $redis;
	}
	
	private function __clone()
	{
		// TODO: Implement __clone() method.
	}
	
	/**
	 * redis 连接池
	 *
	 * @author  chenhuan  2023/1/9
	 * @return void
	 */
	private static function longConnect()
	{
		$pool = new RedisPool((new RedisConfig)
			->withHost(self::$config->getHost())
			->withPort(self::$config->getPort())
			->withAuth(self::$config->getAuth())
			->withDbIndex(self::$config->getSelect())
			->withTimeout(1), self::$config->getMaxResources()
		);
		self::$redisPool = $pool;
	}
	
	/**
	 * 归还链接
	 *
	 * @author  chenhuan  2023/1/9
	 * @param $redis
	 * @return void
	 */
	public static function giveBackRedis($redis)
	{
		return self::$redisPool->put($redis);
	}
}